import 'dart:io';

import 'package:amoy_ticket/utils/alert.dart';
import 'package:amoy_ticket/utils/router/log_util.dart';
import 'package:amoy_ticket/utils/router/router_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

// ignore: must_be_immutable
class CommonParentWidget extends StatefulWidget {
  Widget childWidget;
  CommonParentWidget(this.childWidget);
  @override
  _CommonParentWidgetState createState() => new _CommonParentWidgetState();
}

class _CommonParentWidgetState extends State<CommonParentWidget> {
  late DateTime lastPopTime;

  @override
  Widget build(BuildContext context) {
    if (Platform.isIOS) {
      return Container(
        child: widget.childWidget,
      );
    } else {
      return WillPopScope(
        child: widget.childWidget,
        onWillPop: _requestPop,
      );
    }
  }

  Future<bool> _requestPop() async {
    // 点击返回键的操作
    if (DateTime.now().difference(lastPopTime) > Duration(seconds: 2)) {
      bool backFlag = Navigator.canPop(context);
      if (!backFlag) {
        lastPopTime = DateTime.now();
        LogUtil.get().i('当前页面已经没得返回了,准备退出吧');
        Alert('再按一次退出');
      } else {
        RouterUtil.pop(context);
        return false;
      }
    } else {
      lastPopTime = DateTime.now();
      // 退出app
      await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
      return false;
    }

    return true;
  }
}
